import { Rect, view } from "cc";
import { UIID } from "../../game/config/Config";
import { PlayerMgr } from "../../game/manager/PlayerMgr";
import { Platform } from "../base/BasePlatform";
import { ADType, BaseEventName } from "../config/Appcfg";
import { HttpMgr } from "../network/HttpMgr";
import { AudioMgr } from "./AudioMgr";
import { EventMgr } from "./EventMgr";
import { LogMgr } from "./LogMgr";
import { PlatformManager } from "./PlatformManager";
import { UIMgr } from "./UIMgr";

export class SDKMgr {
    private static instance: SDKMgr = null;
    protected constructor() { }
    public static getInstance(): SDKMgr {
        if (this.instance == null) {
            this.instance = new SDKMgr();
        }
        return this.instance;
    }

    private ShenHeId: number = 0;
    //判断是否审核模式
    public isShenHeModel() {
        if (this.ShenHeId == 2) {
            return true;
        }
        return false;
    }

    //是否编辑器模式
    isEditorPlatform() {
        if (PlatformManager.currentPlatform == Platform.EDITOR) {
            return true;
        }
        return false;
    }
    isReporter_roleInfo: boolean = false;
    /**订阅 */
    eventReporter_roleInfo() {
        if (PlatformManager.currentPlatform == Platform.EDITOR) {
            console.log("hzc____________上报角色信息统计")
            return;
        }
        if (PlatformManager.currentPlatform == Platform.BYTEDANCE) {
            return;
        }
        // this.isReporter_roleInfo = true;
        PlayerMgr.getInstance().getUserData().SetDayDY(true)
        window['qingjs']&&window['qingjs'].instance.reportRoleInfo({

            roleId: "",            // string
            roleName: "",        // string
            roleLevel: 1,                // int 角色等级
            serverId: "",        // string 区服ID需要唯一标识玩家所在区服，如果同时有区ID和服务器ID，请用竖线 “|” 连接起来
            serverName: "",    // string
            roleVip: 1,                    // int 角色vip等级
            rolePower: 1,              // int 战力、武力之类角色的核心数值
            roleGold: 1,                // int 次要货币(非氪金、游戏内可得货币)
            roleDiamond: 1,             // int 主要货币(氪金获得)   
            reportType: "entergame",   // string 上报类型 "entergame" , "createrole", "roleupgrade"

        }, function (result) {

            console.log(window['qingjs']&&window['qingjs'].instance.canPay());

        });
    }

    //是否抖音平台
    isBytedancePlatform() {
        if (PlatformManager.currentPlatform == Platform.BYTEDANCE) {
            return true;
        }
        return false;
    }

    init() {
    }

    //登录
    public login(callback: Function) {
        if (PlatformManager.currentPlatform == Platform.EDITOR) {
            if (callback) {
                callback(404);
            }
            return;
        }
        console.log("hzc___________qingjs", window['qingjs'],window['moduleFunction'])
        if(!window['qingjs']){
            console.warn("登录结束回调数据,SKD不存在，引用错误");
            if (callback) {
                callback();
            }
        }else{
            let isLoginCompelet = false
            window['qingjs'].instance.login({}, function (loginResult) {
                loginResult.code // 200 为成功，其他则失败
                loginResult.uid // 用来标记唯一用户
                loginResult.token // 用户token
                loginResult.message // 登录结果描述
                console.log("登录结束回调数据",loginResult);
                console.log(loginResult);
                PlayerMgr.getInstance().uid = loginResult.uid
                PlayerMgr.getInstance().token = loginResult.token
                if (callback&&!isLoginCompelet) {
                    callback();
                }
                isLoginCompelet = true;
                clearTimeout(checkLoginStaut)
            });
            var checkLoginStaut = setTimeout(()=>{
                if(!isLoginCompelet){
                    console.warn("登录失败，直接进入游戏");
                    isLoginCompelet = true
                    if (callback) {
                        callback(404);
                    }
                }
            },8*1000)
        }
    }

    //上报进入关卡数据
    eventReporter_enterStage(stage: string) {
        this.saveUserData()
        if (PlatformManager.currentPlatform == Platform.EDITOR) {
            console.log("hzc____________进入关卡统计")
            return;
        }
        // window['qingjs']&&window['qingjs'].instance.eventReporter.enterStage(stage)
    }
    
    saveUserData() {
        console.log("保存用户数据:",PlayerMgr.instance.isCanSave)
        if(!PlayerMgr.instance.isCanSave){
            return
        }
        if(!PlayerMgr.instance.userCloudData|| PlayerMgr.instance.userCloudData.level<=PlayerMgr.instance.getUserData().getLevel()){
            HttpMgr.getInstance().saveUserData(PlayerMgr.instance.uid,PlayerMgr.instance.getUserData().data)
        }else{
            console.log('已存在',PlayerMgr.instance.getUserData().getLevel())
        }
    }
    //上报退出关卡数据
    eventReporter_exitStage(stage: string, passStage: boolean, doublePoints: boolean = false, rebirthTimes: number = 0, promptTimes: number = 0) {
        if (PlatformManager.currentPlatform == Platform.EDITOR) {
            console.log("hzc____________退出关卡统计", passStage)
            return;
        }
        // window['qingjs']&&window['qingjs'].instance.eventReporter.exitStage(stage, passStage)
    }
    // //上报激励广告数据
    // eventReporter_showAdButton() {

    // }
    // //上报激励广告数据
    // eventReporter_showAdButton() {

    // } 
    //展示广告按钮
    eventReporter_showAdButton(opportunity: string) {
        if (PlatformManager.currentPlatform == Platform.EDITOR) {
            console.log("hzc____________展示广告按钮")
            return;
        }
        if (PlatformManager.currentPlatform == Platform.BYTEDANCE) {
            return;
        }
        window['qingjs']&&window['qingjs'].instance.eventReporter.showAdButton({
            adType: "video",
            opportunity: opportunity
        })
    }
    /**点击广告按钮 */
    eventReporter_clickAd(opportunity: string) {
        if (PlatformManager.currentPlatform == Platform.EDITOR) {
            console.log("hzc____________点击广告按钮")
            return;
        }
        if (PlatformManager.currentPlatform == Platform.BYTEDANCE) {
            return;
        }
        window['qingjs']&&window['qingjs'].instance.eventReporter.clickAd({
            adType: "video",
            opportunity: opportunity
        })
    }
    /**展示广告 */
    eventReporter_showAd(opportunity: string) {
        if (PlatformManager.currentPlatform == Platform.EDITOR) {
            console.log("hzc____________展示广告")
            return;
        }
        if (PlatformManager.currentPlatform == Platform.BYTEDANCE) {
            return;
        }
        window['qingjs']&&window['qingjs'].instance.eventReporter.showAd({
            adType: "video",
            opportunity: opportunity
        })
    }
    /**完整观看广告 */
    eventReporter_completeAd(opportunity: string) {
        PlayerMgr.instance.isCanSave = true
        if (PlatformManager.currentPlatform == Platform.EDITOR) {
            console.log("hzc____________完整观看广告")
            return;
        }
        if (PlatformManager.currentPlatform == Platform.BYTEDANCE) {
            return;
        }
        console.log("上传",window['qingjs'])
        window['qingjs']&&window['qingjs'].instance.eventReporter.completeAd({
            adType: "video",
            opportunity: opportunity
        })
    }

    /**分享 */
    public share(callback?: Function) {
        if (PlatformManager.currentPlatform == Platform.EDITOR) {
            if (callback) {
                callback(true);
            }
            console.log("编辑器无分享模式");
            return;
        }
        //关闭背景音乐 
        AudioMgr.getInstance().pauseAllMusic()
        //阻止所有的点击事件 前提是打开了UITouch
        EventMgr.getInstance().emit(BaseEventName.blocktouch, false)

        PlatformManager.getInstance().share("", () => {
            EventMgr.getInstance().emit(BaseEventName.blocktouch, true)
            AudioMgr.getInstance().resumeAllMusic()
            if (callback) {
                callback();
            }
        });
    }


    //看视频
    public playVideo(callback: Function, _ADTYPE: ADType): boolean {
        if (PlatformManager.currentPlatform == Platform.EDITOR) {
            if (callback) {
                callback(true);
            }
            PlayerMgr.instance.isCanSave = true
            console.log("编辑器无广告模式");
            return;
        }
        //关闭背景音乐 
        AudioMgr.getInstance().pauseAllMusic()
        this.eventReporter_clickAd(_ADTYPE)
        //阻止所有的点击事件 前提是打开了UITouch
        EventMgr.getInstance().emit(BaseEventName.blocktouch, false)
        PlatformManager.getInstance().showVideoAd(_ADTYPE, 1, () => {
            EventMgr.getInstance().emit(BaseEventName.blocktouch, true)
            AudioMgr.getInstance().resumeAllMusic()
            this.eventReporter_completeAd(_ADTYPE)
            this.eventReporter_showAd(_ADTYPE)
            if (callback) {
                callback(true);
            }
        }, (tips: string) => {
            AudioMgr.getInstance().resumeAllMusic()
            EventMgr.getInstance().emit(BaseEventName.blocktouch, true)
            LogMgr.getInstance().debug("播放广告失败")
            this.eventReporter_showAd(_ADTYPE)
            if (tips && tips.length) {
                UIMgr.getInstance().openUI(UIID.UITips, UIID.Default, tips);
            }
            if (callback) {
                callback(false);
            }

        });
    }

    //审核
    switchGameConfig(callback: Function) {
        if (PlatformManager.currentPlatform == Platform.EDITOR) {
            if (callback) {
                callback(0);
            }
            return;
        }
        if(!window['qingjs']){
            if (callback) {
                callback();
            }
            return
        }
        window['qingjs'].instance.config.switchGameConfig().then(data => {
            console.log(data);
            this.ShenHeId = data.config.game;
            if (callback) {
                callback();
            }
        })
    }

    //悬浮球
    showMenu() {
        if (PlatformManager.currentPlatform != Platform.WECHAT) {
            return;
        }
        window['qingjs']&&window['qingjs'].instance.showMenu({
            canvas: null,  // 微信小游戏上屏canvas
            entryIconX: 0,  // 可选
            entryIconY: 0,  // 可选
        })
    }

    hasVerify(): boolean {
        return PlatformManager.getInstance().hasVerify()
    }
    /**录屏 */
    recordScreen() {
        PlatformManager.getInstance().recordVideo()
    }
    /**暂停录 */
    pauseRecord() {
        PlatformManager.getInstance().pauseRecord()
    }
    restartRecord() {
        PlatformManager.getInstance().resumeRecord()
    }
    /**继续录 */
    resumeRecord() {
        PlatformManager.getInstance().resumeRecord()
    }

    /**分享图片 */
    public shareImg(arg: string, callback: Function) {
        PlatformManager.getInstance().shareImg(arg, callback)
    }

    /**分享录屏 */
    public shareVideo(path: string, callback: Function) {
        PlatformManager.getInstance().shareVideo(path, callback)
    }
    /**是否有分享 */
    public getShare(): boolean {
        return PlatformManager.getInstance().canShare();
    }
    /**
       *  停止录屏  
       * @param isShare 是否分享
       * @param callback 必须调用 回调 返回录屏的路径
       */
    public stopRecord(isShare: boolean, callback: Function) {
        PlatformManager.getInstance().stopRecorderManager(isShare, callback)
    }

    //收藏
    public addCollect(callback: Function) {
        PlatformManager.getInstance().addCollect(callback);
    }

    //添加桌面
    public addDesktop(callback: Function) {
        PlatformManager.getInstance().addDesktop(callback);

    }

    //是否已经领取侧边栏奖励
    isCanShowBagForSideBar: boolean = false;
    //检测是否支持跳转侧边栏
    checkSideBar() {
        PlatformManager.getInstance().checkSideBar((isExist: boolean) => {
            this.isCanShowBagForSideBar = isExist;
        });
    }
    //是否从侧边栏进入
    isEnterGameFromSideBar: boolean = false;
    //前台监听
    public receptionListen() {
        PlatformManager.getInstance().receptionListen((res) => {
            if (res) {
                console.log("启动参数：", res.query);
                console.log("来源信息：", res.refererInfo);
                console.log("场景值：", res.scene);
                console.log("启动场景字段：", res.launch_from, ", ", res.location);
                //判断是从抖音侧边栏进入游戏且未领取过奖励
                if (res.launch_from) {
                    this.isEnterGameFromSideBar = true;
                }
            }
        });
    }
    /**游戏圈 */
    createGameClubButton(rect, callback) {
        return PlatformManager.getInstance().createGameClubButton(rect, callback);
    }
    //跳转抖音侧边栏
    jumpSidebar() {
        PlatformManager.getInstance().jumpSidebar();
    }

    //数据上报
    reportEvent(eventId: string, data: Object) {
        LogMgr.getInstance().logInfo("hzc___________________数据上报", eventId);
        data['test_type'] = PlayerMgr.instance.ConifgName;
        data['new_user'] = PlayerMgr.instance.userData.getIsNewUsers()?"新用户":"老用户";
        PlatformManager.getInstance().reportEvent(eventId, data);
    }

    //震动
    shark(args?: any, callback?: Function) {
        if (!PlayerMgr.getInstance().getUserData().getShark()) {
            return;
        }
        PlatformManager.getInstance().shark(args, callback);
    }
    createFeedbackButton(rect:Rect, callback?: Function) {
        // 通过 wx.getSetting 查询用户是否已授权头像昵称信息
        if(!window['wx']) return;
        let screenSize = view.getVisibleSize();
        let systemInfo = wx.getSystemInfoSync();
        //当前sdk版本
        let screenWidth = systemInfo.screenWidth;
        let screenHeight = systemInfo.screenHeight;
        // 否则，先通过 wx.createFeedbackButton 接口发起授权
        let leftPos = (rect.x - (rect.width / 2)) * screenWidth / screenSize.width;
        let topPos = ((screenSize.height - rect.y) - (rect.height / 2)) * screenHeight / screenSize.height;
        let trueWidth = rect.width * screenWidth / screenSize.width;
        let trueHeight = rect.height * screenHeight / screenSize.height;
        let feedbackButton = wx.createFeedbackButton({
            type: 'text',
            text: '',
            style: {
                left: leftPos,
                top: topPos,
                width: trueWidth,
                height: trueHeight,
                lineHeight: 40,
                backgroundColor: '#00000000',
                color: '#00000000',
                textAlign: 'center',
                fontSize: 16,
                borderRadius: 4
            }
        })
        feedbackButton.onTap(() => {
            if (callback) {
                callback();
            }
        });
        return feedbackButton;
        // this.feedbackButtonOnTap(userInfoButton, callback);
        // return userInfoButton;
    }
}
